package com.example.batchprocessing.partition.local;

import com.example.batchprocessing.Person;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

// 步骤范围声明，分片的时候一个分片一个实例
@StepScope
@Slf4j
@Service
public class PartReaderTest<T extends Person> extends AbstractItemCountingItemStreamItemReader {

  @Value("#{stepExecutionContext['pkt.minValue']}")
  private Integer minValue;
  @Value("#{stepExecutionContext['pkt.maxValue']}")
  private Integer maxValue;
  private String prefix = "pkt";

  @Override
  protected Object doRead() throws Exception {
    Person person = new Person("test", getCurrentItemCount() + "");
    int n = new Random().nextInt(100);
    log.info("测试 read:{} ,maxValue:{}, getCurrentItemCount:{}", person, maxValue, getCurrentItemCount());
    if (getCurrentItemCount() * 6000 > (maxValue - minValue)) {
      return null;
    }
    return person;
  }

  @Override
  protected void doOpen() throws Exception {
    setName(prefix);
    setMaxItemCount(maxValue - minValue);
    log.info("开始读取 maxValue:{}, minValue:{}", maxValue, minValue);
  }

  @Override
  protected void doClose() throws Exception {
    log.info("读取结束 maxValue:{}, getCurrentItemCount:{}", maxValue, getCurrentItemCount());
  }
}
